import express from 'express';
import { verifyAccessToken } from '../middleware/auth.js';
import db from '../config/db.js';

const router = express.Router();

// 根据手机号获取用户信息接口（不需要认证，用于测试）
router.get('/phone/:phone', async (req, res) => {
  try {
    const phone = req.params.phone;
    
    // 查询用户详细信息，根据图片中的字段
    const result = await db.pool.promise().execute(
      'SELECT id, phone, username, weight, height, birthday, img FROM user WHERE phone = ?',
      [phone]
    );
    
    const rows = result[0];
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const user = rows[0];
    // 格式化生日为 yyyy-MM-dd 格式
    let formattedBirthday = '1990-01-01';
    if (user.birthday) {
      const date = new Date(user.birthday);
      formattedBirthday = date.toISOString().split('T')[0];
    }
    
    res.json({
      id: user.id,
      name: user.username || '用户',
      phone: user.phone || '',
      avatar: user.img || null,
      weight: user.weight ? `${user.weight}kg` : '未设置',
      height: user.height ? `${user.height}cm` : '未设置',
      birthday: formattedBirthday,
      created_at: '',
      updated_at: ''
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 根据手机号更新用户信息接口（不需要认证，用于测试）
router.put('/phone/:phone', async (req, res) => {
  try {
    console.log('收到PUT请求:', req.params.phone, req.body);
    const phone = req.params.phone;
    const { name, weight, height, birthday, img } = req.body;
    
    // 处理空字符串，转换为null或合适的默认值
    const processedWeight = weight === '' || weight === null ? null : parseFloat(weight);
    const processedHeight = height === '' || height === null ? null : parseFloat(height);
    const processedBirthday = birthday === '' || birthday === null ? null : birthday;
    
    console.log('准备更新数据:', { phone, name, weight: processedWeight, height: processedHeight, birthday: processedBirthday });
    
    // 更新用户信息，根据图片中的字段
    const result = await db.pool.promise().execute(
      'UPDATE user SET username = ?, weight = ?, height = ?, birthday = ?, img = ? WHERE phone = ?',
      [name, processedWeight, processedHeight, processedBirthday, img || null, phone]
    );
    
    console.log('数据库更新结果:', result);
    
    res.json({
      message: '用户信息更新成功',
      user: {
        phone,
        name,
        weight,
        height,
        birthday
      }
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取用户信息接口（需要认证）
router.get('/profile', verifyAccessToken, async (req, res) => {
  try {
    const phone = req.user.phone;
    
    // 查询用户详细信息，根据图片中的字段
    const result = await db.pool.promise().execute(
      'SELECT id, phone, username, weight, height, birthday, img FROM user WHERE phone = ?',
      [phone]
    );
    
    const rows = result[0];
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const user = rows[0];
    // 格式化生日为 yyyy-MM-dd 格式
    let formattedBirthday = '1990-01-01';
    if (user.birthday) {
      const date = new Date(user.birthday);
      formattedBirthday = date.toISOString().split('T')[0];
    }
    
    res.json({
      id: user.id,
      name: user.username || '用户',
      phone: user.phone || '',
      avatar: user.img || null,
      weight: user.weight ? `${user.weight}kg` : '未设置',
      height: user.height ? `${user.height}cm` : '未设置',
      birthday: formattedBirthday,
      created_at: '',
      updated_at: ''
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新用户信息接口（需要认证）
router.put('/profile', verifyAccessToken, async (req, res) => {
  try {
    console.log('收到更新用户信息请求');
    console.log('用户信息:', req.user);
    console.log('请求体:', req.body);
    
    const phone = req.user.phone;
    const { name, weight, height, birthday, img } = req.body;
    
    // 处理空字符串，转换为null或合适的默认值
    const processedWeight = weight === '' || weight === null ? null : parseFloat(weight);
    const processedHeight = height === '' || height === null ? null : parseFloat(height);
    const processedBirthday = birthday === '' || birthday === null ? null : birthday;
    
    console.log('准备更新数据:', { phone, name, weight: processedWeight, height: processedHeight, birthday: processedBirthday });
    
    // 更新用户信息，根据图片中的字段
    const result = await db.pool.promise().execute(
      'UPDATE user SET username = ?, weight = ?, height = ?, birthday = ?, img = ? WHERE phone = ?',
      [name, processedWeight, processedHeight, processedBirthday, img || null, phone]
    );
    
    console.log('数据库更新结果:', result);
    
    res.json({
      message: '用户信息更新成功',
      user: {
        phone,
        name,
        weight,
        height,
        birthday
      }
    });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

export default router;